

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="风间">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. 分布式会话1.1 什么是会话？会话 session 代表的是客户端与服务器的一次交互过程，这个过程可以是连续的也可以是时断时续的.曾经的 servlet 时代（jsp），一旦用户与服务端交互，tomcat 服务器就会为用户创建一个 session，同时前端会有一个 jsessionid，每次交互都会携带。如此一来, 服务器只要在接收到用户请求的时候，就可以拿到 jsessionid，并根据这">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式会话">
<meta property="og:url" content="http://example.com/2023/05/08/%E5%90%8E%E7%AB%AF/java/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BC%9A%E8%AF%9D/index.html">
<meta property="og:site_name" content="风间小栈">
<meta property="og:description" content="1. 分布式会话1.1 什么是会话？会话 session 代表的是客户端与服务器的一次交互过程，这个过程可以是连续的也可以是时断时续的.曾经的 servlet 时代（jsp），一旦用户与服务端交互，tomcat 服务器就会为用户创建一个 session，同时前端会有一个 jsessionid，每次交互都会携带。如此一来, 服务器只要在接收到用户请求的时候，就可以拿到 jsessionid，并根据这">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s3.bmp.ovh/imgs/2023/04/28/fa0e3149a27c1251.jpg">
<meta property="article:published_time" content="2023-05-08T01:46:03.866Z">
<meta property="article:modified_time" content="2023-05-08T01:46:03.866Z">
<meta property="article:author" content="风间">
<meta property="article:tag" content="redis">
<meta property="article:tag" content="分布式会话">
<meta property="article:tag" content="单点登录">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://s3.bmp.ovh/imgs/2023/04/28/fa0e3149a27c1251.jpg">
  
  
  <title>分布式会话 - 风间小栈</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"§"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>风间小栈</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/%E6%96%87%E6%9C%AC.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="分布式会话">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2023-05-08 09:46" pubdate>
        2023年5月8日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      58 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">分布式会话</h1>
            
            <div class="markdown-body">
              <h2 id="1-分布式会话"><a href="#1-分布式会话" class="headerlink" title="1. 分布式会话"></a>1. 分布式会话</h2><h3 id="1-1-什么是会话？"><a href="#1-1-什么是会话？" class="headerlink" title="1.1 什么是会话？"></a>1.1 什么是会话？</h3><p>会话 session 代表的是客户端与服务器的一次交互过程，这个过程可以是连续的也可以是时断时续的.曾经的 servlet 时代（jsp），一旦用户与服务端交互，tomcat 服务器就会为用户创建一个 session，同时前端会有一个 jsessionid，每次交互都会携带。如此一来, 服务器只要在接收到用户请求的时候，就可以拿到 jsessionid，并根据这个 id 在内存中找到对应的会话 session，当拿到 session 会话后，那么我们就可以操作会话了。会话存活期间，我们就能认为用户一直处于正在使用着网站的状态，一旦 session 超期过时，那么就可以认为用户已经离开网站，停止交互了。用户的身份信息，我们也是通过 session 来判断的，在 session 中可以保存不同用户的信息。</p>
<p>session 的使用方式如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/setSession&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">setSession</span><span class="hljs-params">(HttpServletRequest request)</span> </span>&#123;<br>    HttpSession session = request.getSession();<br>    session.setAttribute(<span class="hljs-string">&quot;userInfo&quot;</span>, <span class="hljs-string">&quot;new user&quot;</span>);<br>    session.setMaxInactiveInterval(<span class="hljs-number">3600</span>);<br>    session.getAttribute(<span class="hljs-string">&quot;userInfo&quot;</span>);<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;ok&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="1-2-无状态会话"><a href="#1-2-无状态会话" class="headerlink" title="1.2 无状态会话"></a>1.2 无状态会话</h3><ul>
<li><p>HTTP 请求是无状态的，用户向服务端发起多次请求，服务端并不会知道这么多次请求都来自同一个用户，这个就是无状态的。</p>
</li>
<li><p>cookie 的出现就是为了有状态的记录用户。</p>
</li>
<li><p>常见的，ios 与服务端交互，安卓与服务端交互，前后端分离，小程序端与服务端交互，它们都是通过发起 http 请求来调用接口数据的，每次交互服务端都不会拿到客户端的状态，但我们可以通过手段去处理，比如用户每次发起请求的时候携带一个 userid 或 user-token，如此一来，就能让服务端根据 userid 或 token 来获得相应的数据。每个用户的下一次请求都能被服务器识别为同一个用户。</p>
</li>
</ul>
<h3 id="1-3-有状态会话"><a href="#1-3-有状态会话" class="headerlink" title="1.3 有状态会话"></a>1.3 有状态会话</h3><p>Tomcat 中的会话，就是有状态的，一旦用户和服务端交互，就有会话，会话保存了用户的信息，这样用户就有“状态”了，服务端会和每个客户端都保持着这样的一层关系，这个由容器来管理（也就是 tomcat），这个 session 会话是保存到内存空间里的，如此依赖，当不同的用户访问服务端，那么就能通过会话知道谁是谁了。如果用户不再和服务端交互，那么会话则消失，结束了它的生命周期。如此一来，每个用户其实都会有一个会话被维护，这就是有状态会话。</p>
<p>场景：在传统项目或者 jsp 项目中使用的最多的 session 都是有状态的，session 的存在就是为了弥补 http 的无状态。</p>
<p><strong>提示：</strong>tomcat 会话可以通过手段实现多系统之间的状态同步，但是会损耗一定的时间，一旦发生同步那么用户请求就会等待，这种做法不可取。</p>
<h3 id="1-4-为何使用无状态会话"><a href="#1-4-为何使用无状态会话" class="headerlink" title="1.4 为何使用无状态会话"></a>1.4 为何使用无状态会话</h3><ul>
<li>有状态的会话都是放在服务器的内存中的，一旦用户会话量多，那么内存就会出现瓶颈。而无状态会话可以采用介质，前端可以使用 cookie（app 可以使用缓存）保存用户 id 或 token，后端比如 redis，相应的用户会话都能放入 redis 中进行管理，如此，对应用部署的服务器就不会造成内存压力。用户在前端发起 http 请求，携带 id 或 token，这样服务器就能根据前端提供的 id 或 token 来识别用户了，可伸缩性就更强了。</li>
</ul>
<h3 id="1-5-单-tomcat-会话"><a href="#1-5-单-tomcat-会话" class="headerlink" title="1.5 单 tomcat 会话"></a>1.5 单 tomcat 会话</h3><ol>
<li><p>先来看下单 tomcat 会话，这个是有状态的，用户首次访问服务端，这时候会话产生，并且会设置 jsessionid 放入 cookie 中，后续每次请求都会携带 jsessionid 以保持用户状态</p>
<p><img src="https://s3.bmp.ovh/imgs/2023/02/07/55ce2336efe4a9ff.png" srcset="/img/loading.gif" lazyload alt="image-20230207211635086"></p>
</li>
</ol>
<h3 id="1-6-动静分离会话"><a href="#1-6-动静分离会话" class="headerlink" title="1.6 动静分离会话"></a>1.6 动静分离会话</h3><ol>
<li><p>动静分离会话</p>
<p>用户请求服务端，由于动静分离，前端发起 http 请求，不会携带任何状态，当用户第一次请求以后，我们手动设置一个 token，作为用户会话，放入 redis 中，如此作为 redis-session，并且这个 token 设置后放入前端 cookie 中（app 或 小程序可以放入本地缓存），如此后续交互中，前端只需传递 token 给后端，后端就能识别这个用户来自谁了</p>
<p><img src="https://s3.bmp.ovh/imgs/2023/02/07/8e65ee153501f181.png" srcset="/img/loading.gif" lazyload></p>
</li>
</ol>
<h3 id="1-7-集群分布式系统会话"><a href="#1-7-集群分布式系统会话" class="headerlink" title="1.7 集群分布式系统会话"></a>1.7 集群分布式系统会话</h3><ol>
<li><p>集群分布式系统会话</p>
<p>集群或分布式系统本质都是多个系统，假设这里有两个服务器节点，分别是AB系统，它们可以是集群，也可以是分布式系统，一开始用户和 A 系统交互，那么这个时候的用户状态，我们可以保存到 redis 中，作为 A 系统的会话信息，随后用户的请求进入到了 B 系统，那么 B 系统中的会话也同样和 redis 关联，如此 AB 系统的 session 就统一了。当然 cookie 是会随着用户的访问携带过来的。那么这个其实就是分布式会话，通过 redis 来保存用户的状态。</p>
<p><img src="https://s3.bmp.ovh/imgs/2023/02/07/b83a6669b4b1264b.png" srcset="/img/loading.gif" lazyload alt="image-20230207212814129"></p>
</li>
</ol>
<h2 id="2-SpringSession-实现用户会话"><a href="#2-SpringSession-实现用户会话" class="headerlink" title="2. SpringSession 实现用户会话"></a>2. SpringSession 实现用户会话</h2><ol>
<li><p>引入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.session<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-session-data-redis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-security<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure></li>
<li><p>新增配置信息</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">spring:</span><br>	<span class="hljs-attr">session:</span><br>		<span class="hljs-attr">store-type:</span> <span class="hljs-string">redis</span><br></code></pre></td></tr></table></figure></li>
<li><p>启动类开启 HttpSession</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@EnableRedisHttpSession</span> <span class="hljs-comment">// 开启使用 redis 作为 SpringSession</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Application</span> </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        SpringApplication.run(Application.class, args);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p>测试</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@GetMapping(&quot;/setSession&quot;)</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">setSession</span><span class="hljs-params">(HttpServletRequest request)</span> </span>&#123;<br>    HttpSession session = request.getSession();<br>    session.setAttribute(<span class="hljs-string">&quot;userInfo&quot;</span>, <span class="hljs-string">&quot;new user&quot;</span>);<br>    session.setMaxInactiveInterval(<span class="hljs-number">3600</span>);<br>    session.getAttribute(<span class="hljs-string">&quot;userInfo&quot;</span>);<br>    <span class="hljs-comment">//        session.removeAttribute(&quot;userInfo&quot;);</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;ok&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="https://s3.bmp.ovh/imgs/2023/02/09/1926998f9275cd16.png" srcset="/img/loading.gif" lazyload alt="image-20230209151107074"></p>
</li>
</ol>
<h2 id="3-分布式会话拦截器"><a href="#3-分布式会话拦截器" class="headerlink" title="3.分布式会话拦截器"></a>3.分布式会话拦截器</h2><blockquote>
<p>基于分布式会话的权限拦截</p>
</blockquote>
<ol>
<li><p>编写拦截器代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><code class="hljs java"><br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserTokenInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HandlerInterceptor</span> </span>&#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String REDIS_USER_TOKEN = <span class="hljs-string">&quot;redis_user_token&quot;</span>;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> RedisOperator redisOperator;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * controller调用之前</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> request</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> response</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> handler</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;进入到拦截器，被拦截... ...&quot;</span>);<br>        String headerUserId = request.getHeader(<span class="hljs-string">&quot;headerUserId&quot;</span>);<br>        String headerUserToken = request.getHeader(<span class="hljs-string">&quot;headerUserToken&quot;</span>);<br><br>        <span class="hljs-keyword">if</span> (StringUtils.isNotBlank(headerUserId) &amp;&amp; StringUtils.isNotBlank(headerUserToken)) &#123;<br>            String uniqueUserToken = <span class="hljs-keyword">this</span>.redisOperator.get(REDIS_USER_TOKEN + <span class="hljs-string">&quot;:&quot;</span> + headerUserId);<br>            <span class="hljs-keyword">if</span> (StringUtils.isBlank(uniqueUserToken)) &#123;<br>                returnErrorResponse(response,JSONResult.errorMsg(<span class="hljs-string">&quot;请登录... ....&quot;</span>));<br>                <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-keyword">if</span> (!Objects.equals(headerUserToken, uniqueUserToken)) &#123;<br>                    returnErrorResponse(response,JSONResult.errorMsg(<span class="hljs-string">&quot;账号在异地登录,请重新登录... ....&quot;</span>));<br>                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            returnErrorResponse(response,JSONResult.errorMsg(<span class="hljs-string">&quot;请登录... ....&quot;</span>));<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;<br>        &#125;<br><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">returnErrorResponse</span><span class="hljs-params">(HttpServletResponse response, JSONResult result)</span> </span>&#123;<br><br>        OutputStream out = <span class="hljs-keyword">null</span>;<br>        response.setCharacterEncoding(<span class="hljs-string">&quot;utf-8&quot;</span>);<br>        response.setContentType(<span class="hljs-string">&quot;text/json&quot;</span>);<br>        <span class="hljs-keyword">try</span> &#123;<br>            out = response.getOutputStream();<br>            out.write(JsonUtils.objectToJson(result).getBytes(StandardCharsets.UTF_8));<br>            out.flush();<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                <span class="hljs-keyword">if</span> (out != <span class="hljs-keyword">null</span>) &#123;<br><br>                    out.close();<br>                &#125;<br>            &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;<br><br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * controller 之后，渲染视图之前</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> request</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> response</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> handler</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> modelAndView</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br><br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * controller 之后，渲染视图之后</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> request</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> response</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> handler</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> ex</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Exception</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">afterCompletion</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure></li>
<li><p>添加拦截器并指定拦截路径</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebMvcConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WebMvcConfigurer</span> </span>&#123;<br><br>    <span class="hljs-comment">// 实现静态资源的映射</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addResourceHandlers</span><span class="hljs-params">(ResourceHandlerRegistry registry)</span> </span>&#123;<br>        registry.addResourceHandler(<span class="hljs-string">&quot;/**&quot;</span>)<br>                .addResourceLocations(<span class="hljs-string">&quot;classpath:/META-INF/resources/&quot;</span>)  <span class="hljs-comment">// 映射swagger2</span><br>                .addResourceLocations(<span class="hljs-string">&quot;file:/workspaces/images/&quot;</span>);  <span class="hljs-comment">// 映射本地静态资源</span><br>    &#125;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> RestTemplate <span class="hljs-title">restTemplate</span><span class="hljs-params">(RestTemplateBuilder builder)</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> builder.build();<br>    &#125;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> UserTokenInterceptor <span class="hljs-title">userTokenInterceptor</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> UserTokenInterceptor();<br>    &#125;<br><br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addInterceptors</span><span class="hljs-params">(InterceptorRegistry registry)</span> </span>&#123;<br>        registry.addInterceptor(userTokenInterceptor())<br>                .addPathPatterns(<span class="hljs-string">&quot;/hello&quot;</span>);<br>        WebMvcConfigurer.<span class="hljs-keyword">super</span>.addInterceptors(registry);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="4-CAS-单点登录"><a href="#4-CAS-单点登录" class="headerlink" title="4. CAS 单点登录"></a>4. CAS 单点登录</h2><h3 id="4-1-相同顶级域名的单点登录-SSO"><a href="#4-1-相同顶级域名的单点登录-SSO" class="headerlink" title="4.1 相同顶级域名的单点登录 SSO"></a>4.1 相同顶级域名的单点登录 SSO</h3><ol>
<li><p>引子</p>
<p>单点登录又称之为 Single Sign On，简称 SSO，单点登录可以通过基于用户会话的共享，分为两种：</p>
<ul>
<li><p>第一种：基于分布式会话实现</p>
<p>比如现在有个一级域名为<code>www.fengjian.tech</code>，是教育类网站，这个网站还有其它产品线，可以通过构建二级域名提供服务给用户访问，比如<code>math.fengjian.tech</code>、<code>english.fengjian.tech</code>等等，分别为数学、英语等，用户只需要在其中一个站点登录，那么其它站点也会随之登录。</p>
</li>
<li></li>
</ul>
</li>
<li><p>Cookie + Redis 实现 SSO</p>
<p>基于 redis 的分布式会话可以流窜在后端的各个系统，都可以获取到 redis 中的用户信息。前端通过使用 cookie （可以保证在同域名下的一级、二级获取）保存用户的 userid 和 token，访问后端时进行携带，用户在任意系统登录后，cookie 和 redis 中都会有用户的信息，只要用户不退出，那么就可以随意登录任意站点了。</p>
<ul>
<li>顶级域名<code>www.fengjian.tech</code>和<code>*.fengjian.tech</code>的 cookie 是可以共享的，都可以携带到后端</li>
<li>二级域名自己独立的 cookie 是不能共享的，<code>math.fengjian.tech</code>和<code>english.fengjian.tech</code>的 cookie 无法实现共享，两者互不影响</li>
</ul>
</li>
<li><p>Cookie 共享测试</p>
<p>打开前端项目：设置域名，必须和 SwitchHosts 中设置的一致</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">cookieDomain: <span class="hljs-string">&quot;.fengjian.tech&quot;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span> math.fengjian.tech<br><span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span> english.fengjian.tech<br></code></pre></td></tr></table></figure></li>
</ol>
<h3 id="4-2-不同顶级域名的单点登录SSO"><a href="#4-2-不同顶级域名的单点登录SSO" class="headerlink" title="4.2 不同顶级域名的单点登录SSO"></a>4.2 不同顶级域名的单点登录SSO</h3><p>  <img src="https://s3.bmp.ovh/imgs/2023/02/09/2a53fb01fd676043.png" srcset="/img/loading.gif" lazyload></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/">后端</a>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BC%9A%E8%AF%9D/">分布式会话</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/redis/">redis</a>
                    
                      <a class="hover-with-bg" href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BC%9A%E8%AF%9D/">分布式会话</a>
                    
                      <a class="hover-with-bg" href="/tags/%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95/">单点登录</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/java/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%83%A8%E7%BD%B2%E9%A1%B9%E7%9B%AE/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">项目部署到云服务器</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/05/08/%E5%90%8E%E7%AB%AF/java/spring%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3%EF%BC%88%E4%B8%89%EF%BC%89/">
                        <span class="hidden-mobile">Spring 核心编程思想（三）：Spring IoC 容器概述</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="SOHUCS" sid='http://example.com/2023/05/08/%E5%90%8E%E7%AB%AF/java/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BC%9A%E8%AF%9D/'></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#SOHUCS', function() {
      Fluid.utils.createScript("https://changyan.sohu.com/upload/changyan.js", function() {
        window.changyan.api.config({"appid":"cywjv2D9l","appkey":"2bf2f1231299e92b26393ba6fb2ad9d8"})
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    风间小栈出品
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
